<template>
  <div class="create-farm">
    <el-container>
      <el-header>
        <div class="header-content">
          <div class="header-left">
            <el-button type="primary" @click="router.push('/')">
              <el-icon><ArrowLeft /></el-icon>
              返回主页
            </el-button>
          </div>
          <div class="header-center">
            <h2>申请创办植物园</h2>
          </div>
        </div>
      </el-header>
      <el-main>
        <el-card class="form-card">
          <el-form
            ref="formRef"
            :model="formData"
            :rules="rules"
            label-width="120px"
            class="farm-form"
          >
            <el-form-item label="农场名称" prop="farmName">
              <el-input v-model="formData.farmName" placeholder="请输入农场名称" />
            </el-form-item>

            <el-form-item label="农场地址" prop="farmAddress">
              <el-input v-model="formData.farmAddress" placeholder="请输入农场地址" />
            </el-form-item>

            <el-form-item label="农场描述" prop="farmDescription">
              <el-input type="textarea" v-model="formData.farmDescription" :rows="3" placeholder="请输入农场描述" />
            </el-form-item>

            <el-form-item label="申请补贴金额" prop="appliedAmount">
              <el-input-number 
                v-model="formData.appliedAmount"
                :min="0"
                :precision="2"
                :step="100"
                placeholder="请输入申请补贴金额"
              />
            </el-form-item>

            <el-form-item label="农场图片" prop="image">
              <el-upload
                class="farm-image-upload"
                :auto-upload="false"
                :show-file-list="true"
                :limit="1"
                accept="image/*"
                :on-change="handleImageChange"
              >
                <template #trigger>
                  <el-button type="primary">选择图片</el-button>
                </template>
                <template #tip>
                  <div class="el-upload__tip">
                    只能上传 jpg/png 文件，且不超过 5MB
                  </div>
                </template>
              </el-upload>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="submitForm">提交申请</el-button>
              <el-button @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-main>
    </el-container>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElLoading } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'
import { addFarm } from '@/api/farms'

const router = useRouter()
const formRef = ref(null)

const formData = reactive({
  farmName: '',
  farmAddress: '',
  farmDescription: '',
  appliedAmount: 0,
  image: null
})

const rules = {
  farmName: [
    { required: true, message: '请输入农场名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  farmAddress: [
    { required: true, message: '请输入农场地址', trigger: 'blur' }
  ],
  farmDescription: [
    { required: true, message: '请输入农场描述', trigger: 'blur' },
    { min: 10, max: 500, message: '描述长度在 10 到 500 个字符', trigger: 'blur' }
  ],
  appliedAmount: [
    { required: true, message: '请输入申请补贴金额', trigger: 'blur' },
    { type: 'number', min: 0, message: '金额必须大于等于0', trigger: 'blur' }
  ],
  image: [
    { required: true, message: '请上传农场图片', trigger: 'change' }
  ]
}

const handleImageChange = (file) => {
  console.log('选择的图片信息:', {
    name: file.name,
    type: file.raw.type,
    size: file.raw.size
  })
  
  // 验证文件类型
  const isImage = file.raw.type.startsWith('image/')
  // 验证文件大小（5MB）
  const isLt5M = file.raw.size / 1024 / 1024 < 5

  if (!isImage) {
    console.log('文件类型验证失败')
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt5M) {
    console.log('文件大小验证失败')
    ElMessage.error('图片大小不能超过 5MB!')
    return false
  }

  console.log('图片验证通过，保存图片')
  formData.image = file.raw
}

const submitForm = async () => {
  if (!formRef.value) return

  try {
    // 表单验证
    console.log('开始表单验证...')
    await formRef.value.validate()
    console.log('表单验证通过')
    
    // 检查是否选择了图片
    console.log('检查图片:', formData.image)
    if (!formData.image) {
      ElMessage.warning('请选择农场图片')
      return
    }

    // 准备表单数据
    const formDataToSend = new FormData()
    formDataToSend.append('farmName', formData.farmName)
    formDataToSend.append('farmAddress', formData.farmAddress)
    formDataToSend.append('farmDescription', formData.farmDescription)
    formDataToSend.append('appliedAmount', formData.appliedAmount)
    formDataToSend.append('image', formData.image)
    
    console.log('准备提交的数据:', {
      farmName: formData.farmName,
      farmAddress: formData.farmAddress,
      farmDescription: formData.farmDescription,
      appliedAmount: formData.appliedAmount,
      imageSize: formData.image.size,
      imageType: formData.image.type
    })

    // 显示加载提示
    const loading = ElLoading.service({
      lock: true,
      text: '提交申请中...',
      background: 'rgba(0, 0, 0, 0.7)'
    })

    try {
      console.log('开始发送请求...')
      const res = await addFarm(formDataToSend)
      console.log('收到响应数据:', res)
      loading.close()

      // 检查是否成功创建农场（通过farmId判断）
      if (res && res.farmId) {
        console.log('判定为成功响应，farmId:', res.farmId)
        ElMessage.success('申请提交成功')
        setTimeout(() => {
          console.log('准备跳转到我的植物园页面')
          router.push('/my-farms')
        }, 1500)
      } else {
        console.log('判定为失败响应，未获取到farmId')
        ElMessage.error('申请提交失败')
      }
    } catch (error) {
      loading.close()
      console.error('请求发生错误:', error)
      console.error('错误详情:', {
        response: error.response,
        message: error.message,
        stack: error.stack
      })
      ElMessage.error(error.response?.data?.message || '提交申请失败，请重试')
    }
  } catch (error) {
    console.error('表单验证失败:', error)
    ElMessage.warning('请填写完整的表单信息')
  }
}

const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
    // 清除已选择的图片
    formData.image = null
  }
}
</script>

<style scoped>
.create-farm {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.el-header {
  padding: 0;
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
  padding: 0 20px;
}

.header-center {
  flex: 1;
  text-align: center;
}

.header-center h2 {
  margin: 0;
  color: #409EFF;
}

.el-main {
  padding: 20px;
  margin-top: 60px;
}

.form-card {
  max-width: 800px;
  margin: 0 auto;
}

.farm-form {
  padding: 20px;
}

.farm-image-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  padding: 20px;
  text-align: center;
}

.farm-image-upload:hover {
  border-color: #409EFF;
}

.el-upload__tip {
  font-size: 12px;
  color: #909399;
  margin-top: 10px;
}
</style> 